<template>
  <div class="mcp-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <div class="title-section">
          <h2 class="page-title">
            <el-icon class="title-icon">
              <Setting />
            </el-icon>
            MCP工具管理
          </h2>
          <p class="page-subtitle">管理和配置MCP工具集，控制工具状态</p>
        </div>
        <div class="header-actions">
          <el-button type="success" @click="showCreateDialog" size="default" round>
            <el-icon>
              <Plus />
            </el-icon>
            新增MCP工具
          </el-button>
          <el-button type="primary" @click="loadMCPTools" :loading="mcpLoading" size="default" round>
            <el-icon>
              <Refresh />
            </el-icon>
            刷新数据
          </el-button>
        </div>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="16">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <el-icon>
                  <Collection />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ pagination.total }}</div>
                <div class="stat-label">MCP工具总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon online">
                <el-icon>
                  <Check />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ getOnlineCount() }}</div>
                <div class="stat-label">已上线</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon testing">
                <el-icon>
                  <Clock />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ getTestingCount() }}</div>
                <div class="stat-label">测试中</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon tools">
                <el-icon>
                  <Tools />
                </el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-number">{{ getTotalToolsCount() }}</div>
                <div class="stat-label">详情工具总数</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- MCP 工具导航区域 -->
    <div class="mcp-navigation">
      <el-card class="navigation-card">
        <template #header>
          <div class="navigation-header">
            <el-icon>
              <Link />
            </el-icon>
            <span>MCP 工具常用导航</span>
          </div>
        </template>
        <div class="navigation-links">
          <el-link href="https://mcp.so/" target="_blank" type="primary" class="nav-link">
            <el-icon>
              <Link />
            </el-icon>
            mcp.so
          </el-link>
          <el-link href="https://github.com/punkpeye/awesome-mcp-servers" target="_blank" type="success"
            class="nav-link">
            <el-icon>
              <Star />
            </el-icon>
            awesome-mcp-servers
          </el-link>
          <el-link href="https://modelscope.cn/mcp" target="_blank" type="warning" class="nav-link">
            <el-icon>
              <Cloudy />
            </el-icon>
            阿里魔搭MCP社区
          </el-link>
        </div>
      </el-card>
    </div>

    <!-- MCP工具列表 -->
    <el-card class="main-card">
      <!-- 搜索区域 -->
      <div class="search-section">
        <el-form :model="searchForm" @submit.prevent="searchMCPTools" inline>
          <el-form-item label="MCP工具名称">
            <el-input v-model="searchForm.mcp_name" placeholder="输入MCP工具名称" clearable style="width: 200px"
              @keyup.enter="searchMCPTools" />
          </el-form-item>
          <el-form-item label="状态">
            <el-select v-model="searchForm.status" placeholder="状态筛选" clearable style="width: 120px"
              @change="searchMCPTools">
              <el-option label="测试中" :value="0" />
              <el-option label="已上线" :value="1" />
              <el-option label="已下线" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item label="接入类型">
            <el-select v-model="searchForm.access_type" placeholder="类型筛选" clearable style="width: 120px"
              @change="searchMCPTools">
              <el-option label="API接入" :value="1" />
              <el-option label="本地工具" :value="2" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="searchMCPTools">
              <el-icon>
                <Search />
              </el-icon>
              搜索
            </el-button>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- MCP工具表格 -->
      <el-table :data="mcpToolsList" v-loading="mcpLoading" style="width: 100%" @row-click="selectMCPTool"
        :row-class-name="getRowClassName" empty-text="暂无MCP工具数据">
        <el-table-column prop="mcp_name" label="MCP工具名称" min-width="180">
          <template #default="scope">
            <div class="mcp-name">
              <el-icon class="mcp-icon">
                <FolderOpened />
              </el-icon>
              <span class="name-text">{{ scope.row.mcp_name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="200" show-overflow-tooltip>
          <template #default="scope">
            <span class="description-text">{{ scope.row.description || '-' }}</span>
          </template>
        </el-table-column>
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusTagType(scope.row.status)" size="small">
              {{ scope.row.status_display }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="接入类型" width="120" align="center">
          <template #default="scope">
            <el-tag :type="getAccessTypeTagType(scope.row.access_type)" size="small">
              {{ scope.row.access_type_display }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="文档URL" width="150" align="center">
          <template #default="scope">
            <el-link v-if="scope.row.doc_url" :href="scope.row.doc_url" target="_blank" type="primary"
              :underline="false">
              <el-icon>
                <Document />
              </el-icon>
              查看文档
            </el-link>
            <span v-else class="text-muted">-</span>
          </template>
        </el-table-column>
        <el-table-column label="工具数量" width="120" align="center">
          <template #default="scope">
            <el-tag type="info" size="small">
              {{ scope.row.tools_count || 0 }} 个
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="启用工具" width="120" align="center">
          <template #default="scope">
            <el-tag type="success" size="small">
              {{ scope.row.enabled_tools_count || 0 }} 个
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180" align="center">
          <template #default="scope">
            {{ formatDate(scope.row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click.stop="viewMCPTools(scope.row)" link>
              <el-icon>
                <View />
              </el-icon>
              查看工具
            </el-button>

            <el-button type="warning" size="small" @click.stop="showEditDialog(scope.row)" link>
              <el-icon>
                <Edit />
              </el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click.stop="deleteMCPTool(scope.row)" link>
              <el-icon>
                <Delete />
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-section">
        <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.page_size"
          :total="pagination.total" :page-sizes="[10, 20, 50, 100]" layout="total, sizes, prev, pager, next, jumper"
          @size-change="searchMCPTools" @current-change="searchMCPTools" background />
      </div>
    </el-card>

    <!-- 工具详情面板 -->
    <el-card v-if="selectedMCPTool" class="tools-detail-card">
      <template #header>
        <div class="detail-header">
          <div class="detail-title">
            <el-icon class="detail-icon">
              <Tools />
            </el-icon>
            <span>{{ selectedMCPTool.mcp_name }} - 详情工具列表</span>
            <el-tag :type="getStatusTagType(selectedMCPTool.status)" size="small" class="mcp-status-tag">
              {{ selectedMCPTool.status_display }}
            </el-tag>
          </div>
          <div class="detail-actions">
            <span class="tool-count">共 {{ detailToolsList.length }} 个工具</span>
          </div>
        </div>
      </template>

      <!-- 详情工具列表 -->
      <el-table :data="detailToolsList" v-loading="toolsLoading" style="width: 100%" empty-text="该MCP工具暂无详情工具">
        <el-table-column prop="id" label="ID" width="80" align="center" />
        <el-table-column prop="tool_name" label="工具名称" min-width="180">
          <template #default="scope">
            <div class="tool-name">
              <el-icon class="tool-icon">
                <Setting />
              </el-icon>
              <span class="name-text">{{ scope.row.tool_name }}</span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="description" label="描述" min-width="250" show-overflow-tooltip />
        <el-table-column label="状态" width="100" align="center">
          <template #default="scope">
            <el-switch v-model="scope.row.is_enabled" active-color="#13ce66" inactive-color="#ff4949"
              @change="(value: boolean) => toggleDetailToolStatus(scope.row, value)"
              :loading="scope.row.statusLoading" />
          </template>
        </el-table-column>
        <el-table-column label="人机交互" width="120" align="center">
          <template #default="scope">
            <el-switch v-model="scope.row.human_interactive_flag" :active-value="1" :inactive-value="0"
              active-color="#409eff" inactive-color="#dcdfe6"
              @change="(value: number) => toggleDetailToolInteractive(scope.row, value)"
              :loading="scope.row.interactiveLoading" />
          </template>
        </el-table-column>
        <el-table-column label="参数数量" width="120" align="center">
          <template #default="scope">
            <el-tag type="info" size="small">
              {{ scope.row.parameters ? scope.row.parameters.length : 0 }} 个
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="180" align="center">
          <template #default="scope">
            <el-button type="primary" size="small" @click="viewToolParams(scope.row)" link
              v-if="scope.row.parameters && scope.row.parameters.length > 0">
              <el-icon>
                <Document />
              </el-icon>
              查看参数
            </el-button>
            <el-button type="warning" size="small" @click="showEditToolDialog(scope.row)" link>
              <el-icon>
                <Edit />
              </el-icon>
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="deleteDetailTool(scope.row)" link>
              <el-icon>
                <Delete />
              </el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 新增/编辑MCP工具对话框 -->
    <el-dialog v-model="mcpDialogVisible" :title="isEditMode ? '编辑MCP工具' : '新增MCP工具'" width="600px"
      @close="closeMCPDialog">
      <el-form ref="mcpFormRef" :model="mcpForm" :rules="mcpFormRules" label-width="120px">
        <el-form-item label="MCP工具名称" prop="mcp_name">
          <el-input v-model="mcpForm.mcp_name" placeholder="请输入MCP工具名称" clearable />
        </el-form-item>
        <el-form-item label="工具描述">
          <el-input v-model="mcpForm.description" type="textarea" :rows="3" placeholder="请输入MCP工具描述（可选）" maxlength="500"
            show-word-limit />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="mcpForm.status" placeholder="请选择状态" style="width: 100%">
            <el-option label="测试中" :value="0" />
            <el-option label="已上线" :value="1" />
            <el-option label="已下线" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="接入类型" prop="access_type">
          <el-select v-model="mcpForm.access_type" placeholder="请选择接入类型" style="width: 100%">
            <el-option label="API接入" :value="1" />
            <el-option label="本地工具" :value="2" />
          </el-select>
        </el-form-item>
        <el-form-item label="文档URL">
          <el-input v-model="mcpForm.doc_url" placeholder="请输入文档URL（可选）" clearable />
        </el-form-item>
        <el-form-item label="JSON配置">
          <el-input v-model="jsonSchemaString" type="textarea" :rows="6" placeholder="请输入JSON配置（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeMCPDialog">取消</el-button>
          <el-button type="primary" @click="saveMCPTool" :loading="saving">
            {{ isEditMode ? '更新' : '创建' }}
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 新增/编辑详情工具对话框 -->
    <el-dialog v-model="toolDialogVisible" title="编辑工具" width="700px" @close="closeToolDialog">
      <el-form ref="toolFormRef" :model="toolForm" :rules="toolFormRules" label-width="120px">
        <el-form-item label="工具名称" prop="tool_name">
          <el-input v-model="toolForm.tool_name" placeholder="请输入工具名称" clearable />
        </el-form-item>
        <el-form-item label="工具描述">
          <el-input v-model="toolForm.description" placeholder="请输入工具描述" clearable />
        </el-form-item>
        <el-form-item label="是否启用">
          <el-switch v-model="toolForm.is_enabled" active-color="#13ce66" inactive-color="#ff4949" />
        </el-form-item>
        <el-form-item label="参数配置">
          <el-input v-model="parametersString" type="textarea" :rows="6" placeholder="请输入参数配置JSON（可选）" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeToolDialog">取消</el-button>
          <el-button type="primary" @click="saveDetailTool" :loading="savingTool">
            更新
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 工具参数查看对话框 -->
    <el-dialog v-model="paramsDialogVisible" title="工具参数详情" width="800px" @close="closeParamsDialog">
      <div class="params-dialog-content">
        <div class="params-header">
          <h4>{{ viewingTool?.tool_name }} - 参数配置</h4>
          <p class="params-description">{{ viewingTool?.description }}</p>
        </div>
        <el-table :data="viewingParams" style="width: 100%" border>
          <el-table-column prop="param_name" label="参数名称" width="150" />
          <el-table-column prop="param_type" label="类型" width="100">
            <template #default="scope">
              <el-tag size="small" :type="getParamTypeColor(scope.row.param_type)">
                {{ scope.row.param_type }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="description" label="描述" min-width="200" />
          <el-table-column prop="default_value" label="默认值" width="120">
            <template #default="scope">
              <code class="default-value">{{ scope.row.default_value || '-' }}</code>
            </template>
          </el-table-column>
          <el-table-column label="是否必需" width="100" align="center">
            <template #default="scope">
              <el-tag :type="scope.row.is_required ? 'danger' : 'success'" size="small">
                {{ scope.row.is_required ? '必需' : '可选' }}
              </el-tag>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance } from 'element-plus'
import {
  Setting, Search, Refresh, Collection, Check, Clock, Tools,
  FolderOpened, View, Edit, Delete, Document, Link, Star, Cloudy, Plus
} from '@element-plus/icons-vue'

// 导入API和类型定义
import {
  mcpApi,
  type MCPTool,
  type MCPToolCreate,
  type MCPToolUpdate,
  type MCPToolSearchParams,
  type DetailTool,
  type DetailToolUpdate
} from '@/api/mcp'

// 响应式数据
const mcpLoading = ref(false)
const toolsLoading = ref(false)
const saving = ref(false)
const savingTool = ref(false)
const mcpToolsList = ref<MCPTool[]>([])
const detailToolsList = ref<DetailTool[]>([])
const selectedMCPTool = ref<MCPTool | null>(null)

// 搜索表单
const searchForm = reactive({
  mcp_name: '',
  status: null as number | null,
  access_type: null as number | null
})

// 分页
const pagination = reactive({
  page: 1,
  page_size: 10,
  total: 0
})

// MCP工具表单
const mcpDialogVisible = ref(false)
const isEditMode = ref(false)
const mcpFormRef = ref<FormInstance>()
const mcpForm = reactive({
  mcp_name: '',
  description: '',
  status: 0,
  access_type: 1,
  doc_url: '',
  json_schema: {}
})
const jsonSchemaString = ref('')

const mcpFormRules = {
  mcp_name: [
    { required: true, message: '请输入MCP工具名称', trigger: 'blur' },
    { min: 1, max: 200, message: '长度在 1 到 200 个字符', trigger: 'blur' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ],
  access_type: [
    { required: true, message: '请选择接入类型', trigger: 'change' }
  ]
}

// 详情工具表单
const toolDialogVisible = ref(false)
const isEditToolMode = ref(false)
const toolFormRef = ref<FormInstance>()
const editingTool = ref<DetailTool | null>(null)
const toolForm = reactive({
  tool_name: '',
  description: '',
  is_enabled: true,
  parameters: []
})
const parametersString = ref('')

const toolFormRules = {
  tool_name: [
    { required: true, message: '请输入工具名称', trigger: 'blur' },
    { min: 1, max: 100, message: '长度在 1 到 100 个字符', trigger: 'blur' }
  ]
}

// 参数查看
const paramsDialogVisible = ref(false)
const viewingParams = ref<any[]>([])
const viewingTool = ref<DetailTool | null>(null)

// 业务方法
const searchMCPTools = async () => {
  mcpLoading.value = true
  try {
    const params: MCPToolSearchParams = {
      page: pagination.page,
      page_size: pagination.page_size
    }

    if (searchForm.mcp_name) {
      params.mcp_name = searchForm.mcp_name
    }
    if (searchForm.status !== null) {
      params.status = searchForm.status
    }
    if (searchForm.access_type !== null) {
      params.access_type = searchForm.access_type
    }

    const result = await mcpApi.getMCPTools(params)
    mcpToolsList.value = (result.items || []).map((item: MCPTool) => ({
      ...item,
      statusLoading: false
    }))
    pagination.total = result.total || 0
  } catch (error) {
    ElMessage.error('获取MCP工具列表失败')
    console.error(error)
  } finally {
    mcpLoading.value = false
  }
}

const loadMCPTools = () => {
  searchMCPTools()
}

const resetSearch = () => {
  searchForm.mcp_name = ''
  searchForm.status = null
  searchForm.access_type = null
  pagination.page = 1
  searchMCPTools()
}

const selectMCPTool = async (row: MCPTool) => {
  selectedMCPTool.value = row
  await loadMCPDetailTools(row.id)
}

const loadMCPDetailTools = async (mcpId: string) => {
  toolsLoading.value = true
  try {
    const result = await mcpApi.getMCPDetailTools(mcpId)
    detailToolsList.value = (result.items || []).map((tool: DetailTool) => ({
      ...tool,
      statusLoading: false
    }))
  } catch (error) {
    ElMessage.error('获取详情工具列表失败')
    console.error(error)
  } finally {
    toolsLoading.value = false
  }
}

const viewMCPTools = async (row: MCPTool) => {
  await selectMCPTool(row)
}

// MCP工具管理
const showCreateDialog = () => {
  isEditMode.value = false
  resetMCPForm()
  mcpDialogVisible.value = true
}

const showEditDialog = (tool: MCPTool) => {
  isEditMode.value = true
  Object.assign(mcpForm, {
    mcp_name: tool.mcp_name,
    description: tool.description || '',
    status: tool.status,
    access_type: tool.access_type,
    doc_url: tool.doc_url || '',
    json_schema: tool.json_schema || {}
  })
  jsonSchemaString.value = tool.json_schema ? JSON.stringify(tool.json_schema, null, 2) : ''
  selectedMCPTool.value = tool
  mcpDialogVisible.value = true
}

const resetMCPForm = () => {
  Object.assign(mcpForm, {
    mcp_name: '',
    description: '',
    status: 0,
    access_type: 1,
    doc_url: '',
    json_schema: {}
  })
  jsonSchemaString.value = ''
  selectedMCPTool.value = null
}

const closeMCPDialog = () => {
  mcpDialogVisible.value = false
  resetMCPForm()
}

const saveMCPTool = async () => {
  if (!mcpFormRef.value) return

  try {
    await mcpFormRef.value.validate()

    saving.value = true

    // 解析JSON配置
    let jsonSchema = null
    if (jsonSchemaString.value.trim()) {
      try {
        jsonSchema = JSON.parse(jsonSchemaString.value)
      } catch (e) {
        ElMessage.error('JSON配置格式错误')
        return
      }
    }

    const data = {
      ...mcpForm,
      json_schema: jsonSchema
    }

    if (isEditMode.value && selectedMCPTool.value) {
      // 更新
      await mcpApi.updateMCPTool(selectedMCPTool.value.id, data as MCPToolUpdate)
      ElMessage.success('MCP工具更新成功')
    } else {
      // 创建
      await mcpApi.createMCPTool(data as MCPToolCreate)
      ElMessage.success('MCP工具创建成功')
    }

    closeMCPDialog()
    await searchMCPTools()
  } catch (error) {
    ElMessage.error(isEditMode.value ? '更新失败' : '创建失败')
    console.error(error)
  } finally {
    saving.value = false
  }
}

const deleteMCPTool = async (tool: MCPTool) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除MCP工具 "${tool.mcp_name}" 吗？这将同时删除其下的所有详情工具。`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await mcpApi.deleteMCPTool(tool.id)
    ElMessage.success('MCP工具删除成功')

    if (selectedMCPTool.value?.id === tool.id) {
      selectedMCPTool.value = null
      detailToolsList.value = []
    }

    await searchMCPTools()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 详情工具管理
const showEditToolDialog = (tool: DetailTool) => {
  isEditToolMode.value = true
  editingTool.value = tool
  Object.assign(toolForm, {
    tool_name: tool.tool_name,
    description: tool.description || '',
    is_enabled: tool.is_enabled,
    parameters: tool.parameters || []
  })
  parametersString.value = tool.parameters && tool.parameters.length > 0
    ? JSON.stringify(tool.parameters, null, 2)
    : ''
  toolDialogVisible.value = true
}

const resetToolForm = () => {
  Object.assign(toolForm, {
    tool_name: '',
    description: '',
    is_enabled: true,
    parameters: []
  })
  parametersString.value = ''
  editingTool.value = null
}

const closeToolDialog = () => {
  toolDialogVisible.value = false
  resetToolForm()
}

const saveDetailTool = async () => {
  if (!toolFormRef.value || !selectedMCPTool.value) return

  try {
    await toolFormRef.value.validate()

    savingTool.value = true

    // 解析参数配置
    let parameters = []
    if (parametersString.value.trim()) {
      try {
        parameters = JSON.parse(parametersString.value)
        if (!Array.isArray(parameters)) {
          ElMessage.error('参数配置必须是数组格式')
          return
        }
      } catch (e) {
        ElMessage.error('参数配置JSON格式错误')
        return
      }
    }

    const data = {
      ...toolForm,
      parameters
    }

    if (isEditToolMode.value && editingTool.value) {
      // 更新
      await mcpApi.updateMCPDetailTool(selectedMCPTool.value.id, editingTool.value.id, data as DetailToolUpdate)
      ElMessage.success('工具更新成功')
    }

    closeToolDialog()
    await loadMCPDetailTools(selectedMCPTool.value.id)
    await searchMCPTools() // 更新统计数据
  } catch (error) {
    ElMessage.error('更新失败')
    console.error(error)
  } finally {
    savingTool.value = false
  }
}

const deleteDetailTool = async (tool: DetailTool) => {
  if (!selectedMCPTool.value) return

  try {
    await ElMessageBox.confirm(
      `确定要删除工具 "${tool.tool_name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await mcpApi.deleteMCPDetailTool(selectedMCPTool.value.id, tool.id)
    ElMessage.success('工具删除成功')

    await loadMCPDetailTools(selectedMCPTool.value.id)
    await searchMCPTools() // 更新统计数据
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

const toggleDetailToolStatus = async (tool: DetailTool, newStatus: boolean) => {
  if (!selectedMCPTool.value) return

  tool.statusLoading = true
  try {
    await mcpApi.updateMCPDetailToolStatus(selectedMCPTool.value.id, tool.id, newStatus)
    ElMessage.success(`工具${newStatus ? '启用' : '禁用'}成功`)
    tool.is_enabled = newStatus
    await searchMCPTools() // 更新统计数据
  } catch (error) {
    tool.is_enabled = !newStatus
    ElMessage.error('状态更新失败')
    console.error(error)
  } finally {
    tool.statusLoading = false
  }
}

const toggleDetailToolInteractive = async (tool: DetailTool, newFlag: number) => {
  if (!selectedMCPTool.value) return

  tool.interactiveLoading = true
  try {
    await mcpApi.updateMCPDetailToolInteractive(selectedMCPTool.value.id, tool.id, newFlag)
    ElMessage.success(`工具交互${newFlag === 1 ? '启用' : '禁用'}成功`)
    tool.human_interactive_flag = newFlag
    await searchMCPTools() // 更新统计数据
  } catch (error) {
    tool.human_interactive_flag = 0
    ElMessage.error('交互状态更新失败')
    console.error(error)
  } finally {
    tool.interactiveLoading = false
  }
}

// 参数查看
const viewToolParams = (tool: DetailTool) => {
  viewingTool.value = tool
  viewingParams.value = tool.parameters || []
  paramsDialogVisible.value = true
}

const closeParamsDialog = () => {
  paramsDialogVisible.value = false
  viewingTool.value = null
  viewingParams.value = []
}

// 统计方法
const getOnlineCount = () => {
  return mcpToolsList.value.filter(item => item.status === 1).length
}

const getTestingCount = () => {
  return mcpToolsList.value.filter(item => item.status === 0).length
}

const getTotalToolsCount = () => {
  return mcpToolsList.value.reduce((total, mcp) => {
    return total + (mcp.tools_count || 0)
  }, 0)
}

// 工具方法
const formatDate = (dateString: string) => {
  return new Date(dateString).toLocaleString('zh-CN')
}

const getRowClassName = ({ row }: { row: MCPTool }) => {
  return row.status === 2 ? 'disabled-row' : ''
}

const getStatusTagType = (status: number) => {
  const typeMap: Record<number, string> = {
    0: 'warning',  // 测试中
    1: 'success',  // 已上线
    2: 'danger'    // 已下线
  }
  return typeMap[status] || 'info'
}

const getAccessTypeTagType = (accessType: number) => {
  const typeMap: Record<number, string> = {
    1: 'primary',  // API接入
    2: 'success'   // 本地工具
  }
  return typeMap[accessType] || 'info'
}

const getParamTypeColor = (type: string) => {
  const colorMap: Record<string, string> = {
    'string': 'success',
    'integer': 'primary',
    'float': 'warning',
    'boolean': 'info'
  }
  return colorMap[type] || 'info'
}

// 生命周期
onMounted(() => {
  searchMCPTools()
})
</script>

<style scoped>
.mcp-management {
  min-height: 100vh;
  background: #f5f7fa;
  padding: 20px;
}

/* 页面头部 */
.page-header {
  margin-bottom: 20px;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: white;
  padding: 24px;
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.title-section {
  flex: 1;
}

.page-title {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.title-icon {
  color: #409eff;
  font-size: 28px;
}

.page-subtitle {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-actions {
  display: flex;
  gap: 12px;
}

/* 统计卡片 */
.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

.stat-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  width: 48px;
  height: 48px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.stat-icon.total {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.stat-icon.online {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.stat-icon.testing {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  color: white;
}

.stat-icon.tools {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
  color: white;
}

.stat-info {
  flex: 1;
}

.stat-number {
  font-size: 28px;
  font-weight: 700;
  color: #303133;
  line-height: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-top: 4px;
}

/* MCP导航区域 */
.mcp-navigation {
  margin-bottom: 20px;
}

.navigation-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

.navigation-header {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.navigation-header .el-icon {
  color: #409eff;
  font-size: 18px;
}

.navigation-links {
  display: flex;
  gap: 24px;
  flex-wrap: wrap;
  align-items: center;
}

.nav-link {
  display: flex;
  align-items: center;
  gap: 6px;
  padding: 8px 16px;
  border-radius: 8px;
  background: #f8f9fa;
  transition: all 0.3s ease;
  text-decoration: none;
  font-weight: 500;
}

.nav-link:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.nav-link .el-icon {
  font-size: 14px;
}

/* 主卡片 */
.main-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
  margin-bottom: 20px;
}

.search-section {
  padding: 16px 0;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
}

/* 表格样式 */
.mcp-name,
.tool-name {
  display: flex;
  align-items: center;
  gap: 8px;
}

.mcp-icon,
.tool-icon {
  color: #409eff;
  font-size: 16px;
}

.name-text {
  font-weight: 500;
  color: #303133;
}

.description-text {
  color: #606266;
  font-size: 13px;
  line-height: 1.5;
}

.disabled-row {
  background-color: #fafafa;
  color: #c0c4cc;
}

.disabled-row .name-text {
  color: #c0c4cc;
}

.text-muted {
  color: #909399;
  font-size: 12px;
}

/* 工具详情卡片 */
.tools-detail-card {
  border: none;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  border-radius: 12px;
}

.detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.detail-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.detail-icon {
  color: #409eff;
  font-size: 18px;
}

.mcp-status-tag {
  margin-left: 12px;
}

.detail-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.tool-count {
  font-size: 14px;
  color: #909399;
  background: #f4f4f5;
  padding: 4px 8px;
  border-radius: 4px;
}

/* 分页 */
.pagination-section {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

/* 参数对话框 */
.params-dialog-content {
  padding: 16px 0;
}

.params-header {
  margin-bottom: 20px;
  padding-bottom: 16px;
  border-bottom: 1px solid #ebeef5;
}

.params-header h4 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.params-description {
  margin: 0;
  color: #606266;
  font-size: 14px;
}

.default-value {
  background: #f4f4f5;
  padding: 2px 6px;
  border-radius: 4px;
  font-size: 12px;
  color: #909399;
}

/* 表单对话框 */
.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式 */
@media (max-width: 768px) {
  .mcp-management {
    padding: 12px;
  }

  .header-content {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .stats-cards .el-col {
    margin-bottom: 12px;
  }
}
</style>